<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/15 0015
 * Time: 下午 15:46
 */
class myHelper
{

    public static function cookieKey($key)
    {
        return COOKIE_PRE . $key;
    }

    public static function createFileName() {
        return time() . '_' . substr(mylogin::getMd5Pwd(time()), rand(0, 20), 5);
    }

    public static function getFirstItem(&$arr, $key)
    {
        if (empty($arr))
        {
            return null;
        }
        foreach ($arr as $v)
        {
            if (!isset($v[$key]))
            {
                return null;
            }
            return $v[$key];
        }
    }
    public static function dateDiff($date1, $date2 = null)
    {
        $dateEnd = new DateTime(empty($date2) ? 'now' : $date2);
        $dateStart = new DateTime($date1);
        return $dateEnd->getTimestamp() - $dateStart->getTimestamp();

    }

    public static function getBase64ImageSize($baseStr, $type = '')
    {
        $baseStr = str_replace('=', '', $baseStr);
        $len = strlen($baseStr);
        if ($type == '')
        {
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $baseStr, $result))
            {
                $type = $result[2];
            }
            $type = 3;
        }
        $len = $len - 19 - strlen($type);
        return $len < 0 ? 0 : ($len - ($len / 8) * 2);
    }

    /**
     * @param $base64Str 图片str
     * @param $topath 上传的路径名称，不要后缀,例：up/avatar/avatar_1283232323
     * @param array $exts 大小限制
     * @param int $maxSize 大小限制,-1 为不限制
     * @return string|boolean
     */
    public static function uploadBase64Image($base64Str, &$topath, $tipsHead = "", $maxSize = -1, array $exts = ['png', 'gif', 'jpeg', 'jpg', 'wbmp', 'bmp'])
    {
        $tipsHead = empty($tipsHead) ? '' : $tipsHead;
        //保存base64字符串为图片
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64Str, $result))
        {
            $type = $result[2];

            if (!in_array($type, $exts))
            {
                return $tipsHead . '图片格式错误';
            }
            if ($maxSize > 0 && myHelper::getBase64ImageSize($base64Str) > $maxSize)
            {
                return $tipsHead . '图片大小超过限制';
            }
            $topath = $topath . '.' . $type;
            if (file_put_contents($topath, base64_decode(str_replace($result[1], '', $base64Str))))
            {
                return true;
            }
            return $tipsHead . '图片上传失败';
        }
        else
        {
            return $tipsHead . '图片内容错误';
        }
    }
}